<?php

namespace App\Http\Controllers\Guard\Rbac;

use App\Http\Controllers\Common\GuardController;
use App\Models\Rbac\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class PermissionController extends GuardController {

    public function __construct() {
        $this->instance = new Permission();
    }

    public function lst(Request $request) {
        if($request->has('tree')){
            $conditions = ['pid'=>0];
            $conditions['orderBy']['col'] = 'id';
            $conditions['orderBy']['sort'] = 'asc';
            $records = $this->instance->getLst($conditions)->with(['children'])->get();
            return responseSuccess($records->toArray(),$records->count());
        }else{
            $records = $this->instance->newQuery()->get();
            return responseSuccess($records->toArray(),$records->count());
        }
    }

    public function add(Request $request) {
        try{
            $id = $request->input('id',0);
            $title = $request->input('title');
            $component = $request->input('component');
            $name = $request->input('name');
            $path = $request->input('path');
            $pid = $request->input('pid');
            $lastSortRecord = $this->instance->newQuery()->where('pid',$pid)->orderByDesc('sort')->first();
            $sort =empty($lastSortRecord)?1:$lastSortRecord->sort+1 ;
            $icon = $request->input('icon');
            if(empty($icon))$icon = 'table';
            $redirect = $request->input('redirect');
            $is_show = $request->input('is_show',1);
            $info = compact('name','path','pid','component','sort','icon','title','redirect','is_show');
            $record = $this->instance->updateOrCreate(['id'=>$id],$info);

            return responseSuccess($record->toArray());
        }catch(\Exception $e){
            $msg = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($msg);
            return responseFail($msg);
        }
    }

}
